#include "objc-private.h"
#include <objc/message.h>
#include <map>
#include "DenseMapExtras.h"

// expanded policy bits.

enum {
    OBJC_ASSOCIATION_SETTER_ASSIGN      = 0,
    OBJC_ASSOCIATION_SETTER_RETAIN      = 1,
    OBJC_ASSOCIATION_SETTER_COPY        = 3,            // NOTE:  both bits are set, so we can simply test 1 bit in releaseValue below.
    OBJC_ASSOCIATION_GETTER_READ        = (0 << 8),
    OBJC_ASSOCIATION_GETTER_RETAIN      = (1 << 8),
    OBJC_ASSOCIATION_GETTER_AUTORELEASE = (2 << 8),
    OBJC_ASSOCIATION_SYSTEM_OBJECT      = _OBJC_ASSOCIATION_SYSTEM_OBJECT, // 1 << 16
};

spinlock_t AssociationsManagerLock;

/*
* NOTE:
* 1. AssociationsManager: 是全局单例对象, 维护 AssociationsHashMap 集合.
* 2. AssociationsHashMap: 是一个无序的哈希表, 维护对象内部所有管理记录
Key: 源对象,
value: ObjectAssociationMap的映射.

* 3. ObjectAssociationMap: 一个 C++ 中的 map, 负责维护源对象内部的关联记录.
Key: 传过来的关联Key,
value: ObjcAssociation 对象的映射.

* 4. ObjcAssociation: 关联对象, 是一个 C++ 的类, 表示一个具体的关联结构,
主要包括两个实例变量, _policy 表示关联策略, _value 表示关联对象.
*/
namespace objc {

class ObjcAssociation {
    uintptr_t _policy;
    id _value;
public:
    ObjcAssociation(uintptr_t policy, id value) : _policy(policy), _value(value) {}
    ObjcAssociation() : _policy(0), _value(nil) {}
    ObjcAssociation(const ObjcAssociation &other) = default;
    ObjcAssociation &operator=(const ObjcAssociation &other) = default;
    ObjcAssociation(ObjcAssociation &&other) : ObjcAssociation() {
        swap(other);
    }

    // 交换key & value值
    inline void swap(ObjcAssociation &other) {
        std::swap(_policy, other._policy);
        std::swap(_value, other._value);
    }

    inline uintptr_t policy() const { return _policy; }
    inline id value() const { return _value; }

    inline void acquireValue() {
        if (_value) {
            switch (_policy & 0xFF) {
            case OBJC_ASSOCIATION_SETTER_RETAIN:
                _value = objc_retain(_value);
                break;
            case OBJC_ASSOCIATION_SETTER_COPY:
                _value = ((id(*)(id, SEL))objc_msgSend)(_value, @selector(copy));
                break;
            }
        }
    }

    inline void releaseHeldValue() {
        if (_value && (_policy & OBJC_ASSOCIATION_SETTER_RETAIN)) {
            objc_release(_value);
        }
    }

    inline void retainReturnedValue() {
        if (_value && (_policy & OBJC_ASSOCIATION_GETTER_RETAIN)) {
            objc_retain(_value);
        }
    }

    inline id autoreleaseReturnedValue() {
        if (slowpath(_value && (_policy & OBJC_ASSOCIATION_GETTER_AUTORELEASE))) {
            return objc_autorelease(_value);
        }
        return _value;
    }
};

typedef DenseMap<const void *, ObjcAssociation> ObjectAssociationMap;
// llvm-DenseMap.h
typedef DenseMap<DisguisedPtr<objc_object>, ObjectAssociationMap> AssociationsHashMap;

// class AssociationsManager manages a lock / hash table singleton pair.
// Allocating an instance acquires the lock

class AssociationsManager {
    using Storage = ExplicitInitDenseMap<DisguisedPtr<objc_object>, ObjectAssociationMap>;
    static Storage _mapStorage;

public:
    AssociationsManager()   { AssociationsManagerLock.lock(); }
    ~AssociationsManager()  { AssociationsManagerLock.unlock(); }

    AssociationsHashMap &get() {
        return _mapStorage.get();
    }

    static void init() {
        _mapStorage.init();
    }
};

AssociationsManager::Storage AssociationsManager::_mapStorage;

} // namespace objc

using namespace objc;

/**
 * 初始化入口
 * 什么时候初始化的?
 * dyld`start .......
 * map_images()
 * map_images_nolock()
 * arr_init()
 */
void
_objc_associations_init()
{
    AssociationsManager::init();
}

/**
 * 从源对象取出关联对象值
 * Parameter @object: 关联的源对象
 * Parameter @key:    关联键
 */
id
_object_get_associative_reference(id object, const void *key)
{
    // 声明一个空的关联对象
    ObjcAssociation association{};

    {
        // 全局关联map管理者
        AssociationsManager manager;
        // 得到所有的关联数据
        AssociationsHashMap &associations(manager.get());
        // 根据 源对象 遍历找到源对象内部的关联map
        AssociationsHashMap::iterator i = associations.find((objc_object *)object);
        // 判断迭代器不在最后表示不为空
        if (i != associations.end()) {
            // i->first  得到Key
            // i->second 得到Value
            ObjectAssociationMap &refs = i->second;
            //
            ObjectAssociationMap::iterator j = refs.find(key);
            if (j != refs.end()) {
                association = j->second;
                association.retainReturnedValue();
            }
        }
    }

    return association.autoreleaseReturnedValue();
}

/* 源对象关联某个对象值底层函数
 * Parameter @object: 关联的源对象
 * Parameter @key:    关联键
 * Parameter @value:  关联值
 * Parameter @policy: 策略
 */
void
_object_set_associative_reference(id object, const void *key, id value, uintptr_t policy)
{
    // This code used to work when nil was passed for object and key. Some code
    // probably relies on that to not crash. Check and handle it explicitly.
    // rdar://problem/44094390
    if (!object && !value) return;

    if (object->getIsa()->forbidsAssociatedObjects())
        _objc_fatal("objc_setAssociatedObject called on instance (%p) of class %s which does not allow associated objects", object, object_getClassName(object));

    // 包装成 DisguisedPtr<objc_object>
    DisguisedPtr<objc_object> disguised{(objc_object *)object};
    
    // 初始化一个 ObjcAssociation 类型的 值对象(不是指针(引用对象))
    ObjcAssociation association{policy, value};

    // retain the new value (if any) outside the lock.
    // 根据策略对 对象做retain操作
    association.acquireValue();

    bool isFirstAssociation = false;
    {
        // 声明一个 AssociationsManager类型对象, 但是AssociationsManager内部是个单例
        AssociationsManager manager;
        // 获取全部关联数据
        AssociationsHashMap &associations(manager.get());

        // 关联值
        if (value) { // 不为空, 赋值操作
            // C++17 引入了std::try_emplace,
            // 在参数列表中, 把key和value分开, 该方法会检测指定的key是否存在,
            // 如果存在, 什么也不做, 不存在, 则插入相应的value
            // try_emplace: llvm-DenseMap.h 有实现
            // 知道try_emplace含义后, 可以理解是对 源对象 的 ObjectAssociationMap 初始化操作
            auto refs_result = associations.try_emplace(disguised, ObjectAssociationMap{});
            // 如果是第一次, second 为true
            if (refs_result.second) {
                /* it's the first association we make */
                isFirstAssociation = true;
            }

            /* establish or replace the association */
            // ObjectAssociationMap
            auto &refs = refs_result.first->second;
            
            // C++17引入了std::try_emplace，
            // 在参数列表中，把key和value分开，该方法会检测指定的key是否存在，
            // 如果存在，什么也不做，不存在，则插入相应的value
            // 可以理解是对 ObjectAssociationMap 的 key值 初始化操作
            auto result = refs.try_emplace(key, std::move(association));
            // 如果 key: 对应的value无值 second = true
            // 如果 key: 对应的value有值 second = false
            // 无值是直接移动进key对应值空间内,
            // 有值就不会动 try_emplace 函数特性, 所以需要swap 交换一下
            if (!result.second) {
                association.swap(result.first->second);
            }
        }
        else { // 为空, 清空操作
            // 在 map 容器中查找键为 key 的键值对,
            // 如果成功找到, 则返回指向该键值对的 双向迭代器;
            // 反之, 则返回和 end() 方法一样的迭代器.
            // 另外, 如果 map 容器用 const 限定, 则该方法返回的是 const 类型的双向迭代器
            auto refs_it = associations.find(disguised); // ObjectAssociationMap 类型
            // 判断迭代器不在最后表示不为空
            if (refs_it != associations.end()) {
                // refs->first  得到Key
                // refs->second 得到Value: ObjectAssociationMap 类型
                auto &refs = refs_it->second;
                // 在次查找 key 对应的迭代器
                auto it = refs.find(key); // ObjcAssociation 类型
                // 判断迭代器不在最后表示不为空
                if (it != refs.end()) {
                    // it->first  得到Key
                    // it->second 得到Value: ObjcAssociation 类型
                    // swap: 交换 2 个 map 容器中存储的键值对，这意味着，操作的 2 个键值对的类型必须相同
                    // 因为association这个 是个空值, 所以变相清空了内部值
                    association.swap(it->second);
                    // 删除 map 容器指定位置、指定键（key）值或者指定区域内的键值对
                    refs.erase(it);
                    // 返回当前 map 容器中存有键值对的个数
                    // 如果当前ObjectAssociationMap 为空
                    if (refs.size() == 0) {
                        // 删除 map 容器指定位置、指定键（key）值或者指定区域内的键值对
                        // 删除 ObjectAssociationMap
                        associations.erase(refs_it);
                    }
                }
            }
        }
    }

    // Call setHasAssociatedObjects outside the lock, since this
    // will call the object's _noteAssociatedObjects method if it
    // has one, and this may trigger +initialize which might do
    // arbitrary stuff, including setting more associated objects.
    // 修改object的isa指针, 标记为有关联对象, 在object的dealloc中有用
    if (isFirstAssociation)
        object->setHasAssociatedObjects();

    // release the old value (outside of the lock).
    // 对旧值的释放
    association.releaseHeldValue();
}

// Unlike setting/getting an associated reference,
// this function is performance sensitive because of
// raw isa objects (such as OS Objects) that can't track
// whether they have associated objects.
void
_object_remove_assocations(id object, bool deallocating)
{
    ObjectAssociationMap refs{};

    {
        AssociationsManager manager;
        AssociationsHashMap &associations(manager.get());
        AssociationsHashMap::iterator i = associations.find((objc_object *)object);
        if (i != associations.end()) {
            refs.swap(i->second);

            // If we are not deallocating, then SYSTEM_OBJECT associations are preserved.
            bool didReInsert = false;
            if (!deallocating) {
                for (auto &ref: refs) {
                    if (ref.second.policy() & OBJC_ASSOCIATION_SYSTEM_OBJECT) {
                        i->second.insert(ref);
                        didReInsert = true;
                    }
                }
            }
            if (!didReInsert)
                associations.erase(i);
        }
    }

    // Associations to be released after the normal ones.
    SmallVector<ObjcAssociation *, 4> laterRefs;

    // release everything (outside of the lock).
    for (auto &i: refs) {
        if (i.second.policy() & OBJC_ASSOCIATION_SYSTEM_OBJECT) {
            // If we are not deallocating, then RELEASE_LATER associations don't get released.
            if (deallocating)
                laterRefs.append(&i.second);
        } else {
            i.second.releaseHeldValue();
        }
    }
    for (auto *later: laterRefs) {
        later->releaseHeldValue();
    }
}
